// 获取DOM元素
const serverUrlInput = document.getElementById('serverUrl');
const connectBtn = document.getElementById('connectBtn');
const disconnectBtn = document.getElementById('disconnectBtn');
const terminateSessionBtn = document.getElementById('terminateSessionBtn');
const sessionIdSpan = document.getElementById('sessionId');
const resumptionTokenSpan = document.getElementById('resumptionToken');
const connectionStatusSpan = document.getElementById('connectionStatus');
const serverInfoSpan = document.getElementById('serverInfo');
const pingBtn = document.getElementById('pingBtn');
const listToolsBtn = document.getElementById('listToolsBtn');
const callToolBtn = document.getElementById('callToolBtn');
const completeBtn = document.getElementById('completeBtn');
const setLoggingLevelBtn = document.getElementById('setLoggingLevelBtn');
const listPromptsBtn = document.getElementById('listPromptsBtn');
const getPromptBtn = document.getElementById('getPromptBtn');
const listResourcesBtn = document.getElementById('listResourcesBtn');
const readResourceBtn = document.getElementById('readResourceBtn');
const listResourceTemplatesBtn = document.getElementById('listResourceTemplatesBtn');
const subscribeResourceBtn = document.getElementById('subscribeResourceBtn');
const unsubscribeResourceBtn = document.getElementById('unsubscribeResourceBtn');
const getServerInfoBtn = document.getElementById('getServerInfoBtn');
const customRequestBtn = document.getElementById('customRequestBtn');
const requestMethodSelect = document.getElementById('requestMethod');
const requestParamsInput = document.getElementById('requestParams');
const sendRequestBtn = document.getElementById('sendRequestBtn');
const requestResultTextarea = document.getElementById('requestResult');
const logsDiv = document.getElementById('logs');
const capabilityLogs = document.getElementById('capabilityLogs');
const capabilityPrompts = document.getElementById('capabilityPrompts');
const capabilityResources = document.getElementById('capabilityResources');
const capabilityTools = document.getElementById('capabilityTools');
const capabilityCompletions = document.getElementById('capabilityCompletions');

// 全局变量
let transport = null;
let client = null;
let resumptionToken = null;

// 日志函数
function log(message, type = 'debug') {
    const logEntry = document.createElement('div');
    logEntry.className = `log-entry ${type}`;
    logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
    logsDiv.appendChild(logEntry);
    logsDiv.scrollTop = logsDiv.scrollHeight;
}

// 禁用或启用能力选择框
function disableCapabilityCheckboxes(disabled) {
    const checkboxes = document.querySelectorAll('.capabilities-section input[type="checkbox"]');
    checkboxes.forEach(checkbox => {
        checkbox.disabled = disabled;
    });
}

// 更新UI状态函数
function updateUIState(connected, serverCapabilities = null) {
    connectBtn.disabled = connected;
    disconnectBtn.disabled = !connected;
    terminateSessionBtn.disabled = !connected;
    sendRequestBtn.disabled = !connected;
    
    // 更新API按钮状态
    pingBtn.disabled = !connected;
    getServerInfoBtn.disabled = !connected;
    customRequestBtn.disabled = !connected;
    
    // 如果没有服务器能力信息，默认启用所有按钮（保持向后兼容性）
    if (!serverCapabilities) {
        listToolsBtn.disabled = !connected;
        callToolBtn.disabled = !connected;
        completeBtn.disabled = !connected;
        setLoggingLevelBtn.disabled = !connected;
        listPromptsBtn.disabled = !connected;
        getPromptBtn.disabled = !connected;
        listResourcesBtn.disabled = !connected;
        readResourceBtn.disabled = !connected;
        listResourceTemplatesBtn.disabled = !connected;
        subscribeResourceBtn.disabled = !connected;
        unsubscribeResourceBtn.disabled = !connected;
    } else {
        // 根据服务器实际支持的能力启用相应的按钮
        // 工具相关功能
        const hasTools = serverCapabilities.tools && serverCapabilities.tools.enabled !== false;
        listToolsBtn.disabled = !connected || !hasTools;
        callToolBtn.disabled = !connected || !hasTools;
        
        // 补全相关功能
        const hasCompletions = serverCapabilities.completions && serverCapabilities.completions.enabled !== false;
        completeBtn.disabled = !connected || !hasCompletions;
        
        // 日志相关功能
        const hasLogging = serverCapabilities.logging && serverCapabilities.logging.enabled !== false;
        setLoggingLevelBtn.disabled = !connected || !hasLogging;
        
        // 提示词相关功能
        const hasPrompts = serverCapabilities.prompts && serverCapabilities.prompts.enabled !== false;
        listPromptsBtn.disabled = !connected || !hasPrompts;
        getPromptBtn.disabled = !connected || !hasPrompts;
        
        // 资源相关功能
        const hasResources = serverCapabilities.resources && serverCapabilities.resources.enabled !== false;
        listResourcesBtn.disabled = !connected || !hasResources;
        readResourceBtn.disabled = !connected || !hasResources;
        listResourceTemplatesBtn.disabled = !connected || !hasResources;
        
        // 资源订阅功能需要额外检查是否支持订阅
        const hasResourceSubscription = hasResources && 
                                       serverCapabilities.resources.subscription && 
                                       serverCapabilities.resources.subscription.enabled !== false;
        subscribeResourceBtn.disabled = !connected || !hasResourceSubscription;
        unsubscribeResourceBtn.disabled = !connected || !hasResourceSubscription;
    }
    
    connectionStatusSpan.textContent = connected ? '已连接' : '未连接';
}

// 连接按钮点击事件
connectBtn.addEventListener('click', async () => {
    try {
        const serverUrl = serverUrlInput.value.trim();
        if (!serverUrl) {
            log('请输入服务器 URL', 'error');
            return;
        }
        
        // 检查WebSocket URL格式
        if (!serverUrl.startsWith('ws://') && !serverUrl.startsWith('wss://')) {
            log('警告: WebSocket URL 应以 ws:// 或 wss:// 开头', 'warn');
        }
        
        log(`正在使用WebSocket连接到 ${serverUrl}`, 'info');
        
        // 检查McpClient是否正确加载
        if (typeof window.McpClient === 'undefined') {
            log('错误: McpClient 未正确加载，请检查client.js是否正确引入', 'error');
            return;
        }
        
        // 尝试获取WebSocketClientTransport和Client
        let WebSocketClientTransport = window.McpClient.WebSocketClientTransport || 
                                       (window.McpClient.default && window.McpClient.default.WebSocketClientTransport);
                                            
        let Client = window.McpClient.Client || 
                     (window.McpClient.default && window.McpClient.default.Client);
        
        if (typeof WebSocketClientTransport !== 'function') {
            log('错误: WebSocketClientTransport 不可用', 'error');
            return;
        }
        
        if (typeof Client !== 'function') {
            log('错误: Client 类不可用', 'error');
            return;
        }
        
        // 创建 WebSocketClientTransport 实例
        transport = new WebSocketClientTransport(serverUrl, {
            reconnectionOptions: {
                initialReconnectionDelay: 1000,
                maxReconnectionDelay: 30000,
                reconnectionDelayGrowFactor: 1.5,
                maxRetries: 5
            }
        });
        
        // 设置事件处理器
        transport.onmessage = (message) => {
            log(`收到WebSocket消息: ${JSON.stringify(message)}`, 'info');
        };
        
        transport.onerror = (error) => {
            log(`WebSocket错误: ${error.message || String(error)}`, 'error');
            if (error.message && error.message.includes('Failed to connect') || 
                error.message && error.message.includes('连接失败')) {
                log('提示: 请检查服务器URL是否正确，以及服务器是否正在运行', 'info');
            }
        };
        
        transport.onclose = () => {
            log('WebSocket连接已关闭', 'info');
            updateUIState(false);
        };
        
        transport.onopen = () => {
            log('WebSocket连接已打开', 'info');
            connectionStatusSpan.textContent = '连接中';
        };
        
        // 收集用户选择的客户端能力
        const capabilities = {
            logging: capabilityLogs.checked,
            prompts: capabilityPrompts.checked,
            resources: capabilityResources.checked,
            tools: capabilityTools.checked,
            completions: capabilityCompletions.checked
        };
        
        log(`客户端能力: ${JSON.stringify(capabilities)}`, 'debug');
        
        // 创建 Client 实例
        client = new Client({
            name: "WebSocket Client Demo",
            version: "1.0.0"
        }, {
            capabilities: capabilities
        });
        
        log('开始初始化WebSocket客户端连接...', 'info');
        connectionStatusSpan.textContent = '初始化中';
        
        // 禁用能力选择框
        disableCapabilityCheckboxes(true);
        
        // 直接使用Client API进行初始化，client.connect()会自动处理transport的启动
        await client.connect(transport);
        
        log('WebSocket客户端初始化成功!', 'info');
        connectionStatusSpan.textContent = '已初始化';
        
        // 显示服务器信息
        const serverInfo = client.getServerVersion();
        const serverCapabilities = client.getServerCapabilities();
        
        if (serverInfo) {
            log(`服务器信息: ${JSON.stringify(serverInfo)}`, 'info');
            serverInfoSpan.textContent = `${serverInfo.name || '未知'} v${serverInfo.version || '未知'}`;
        }
        
        if (serverCapabilities) {
            log(`服务器支持的能力: ${JSON.stringify(serverCapabilities)}`, 'info');
        }
        
        // 更新会话ID显示
        if (transport.sessionId) {
            sessionIdSpan.textContent = transport.sessionId;
            log(`已建立WebSocket会话: ${transport.sessionId}`, 'info');
        }
        
        // 启用按钮，并传入服务器能力信息
        updateUIState(true, serverCapabilities);
        
    } catch (error) {
        log(`WebSocket连接失败: ${error.message}`, 'error');
        if (error.response) {
            try {
                const errorBody = await error.response.text();
                log(`服务器错误详情: ${errorBody}`, 'error');
            } catch (e) {
                log(`无法解析服务器错误详情`, 'error');
            }
        }
    }
});

// Ping按钮点击事件
pingBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        log('使用WebSocket Client API发送ping...', 'info');
        await client.ping();
        log('ping 成功!', 'info');
        requestResultTextarea.value = 'Ping 请求成功，服务器已响应';
    } catch (error) {
        log(`ping 失败: ${error.message}`, 'error');
        requestResultTextarea.value = `Ping 请求失败: ${error.message}`;
    }
});

// 列出工具按钮点击事件
listToolsBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        log('使用WebSocket Client API列出工具...', 'info');
        const result = await client.listTools({});
        log(`工具列表: ${JSON.stringify(result.tools)}`, 'info');
        requestResultTextarea.value = JSON.stringify(result, null, 2);
    } catch (error) {
        log(`列出工具失败: ${error.message}`, 'error');
        requestResultTextarea.value = `列出工具失败: ${error.message}`;
    }
});

// 调用工具按钮点击事件
callToolBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        // 先列出工具以获取可用工具信息
        log('正在获取工具列表...', 'info');
        const toolsResult = await client.listTools({});
        
        if (toolsResult.tools && toolsResult.tools.length > 0) {
            const firstTool = toolsResult.tools[0];
            log(`使用WebSocket Client API调用工具: ${firstTool.name}`, 'info');
            
            // 尝试使用第一个工具，传入简单参数
            const result = await client.callTool({
                name: firstTool.name,
                parameters: {}
            });
            
            log(`工具调用结果: ${JSON.stringify(result)}`, 'info');
            requestResultTextarea.value = JSON.stringify(result, null, 2);
        } else {
            log('未找到可用工具', 'info');
            requestResultTextarea.value = '未找到可用工具';
        }
    } catch (error) {
        log(`调用工具失败: ${error.message}`, 'error');
        requestResultTextarea.value = `调用工具失败: ${error.message}`;
    }
});

// 文本补全按钮点击事件
completeBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        log('使用WebSocket Client API进行文本补全...', 'info');
        const result = await client.complete({
            prompt: "请解释什么是MCP协议？",
            maxTokens: 200
        });
        
        log('补全请求成功', 'info');
        requestResultTextarea.value = JSON.stringify(result, null, 2);
    } catch (error) {
        log(`补全请求失败: ${error.message}`, 'error');
        requestResultTextarea.value = `补全请求失败: ${error.message}`;
    }
});

// 设置日志级别按钮点击事件
setLoggingLevelBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        log('使用WebSocket Client API设置日志级别...', 'info');
        await client.setLoggingLevel('debug');
        
        log('日志级别已设置为: debug', 'info');
        requestResultTextarea.value = '日志级别设置成功';
    } catch (error) {
        log(`设置日志级别失败: ${error.message}`, 'error');
        requestResultTextarea.value = `设置日志级别失败: ${error.message}`;
    }
});

// 列出提示词按钮点击事件
listPromptsBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        log('使用WebSocket Client API列出提示词...', 'info');
        const result = await client.listPrompts({});
        
        log(`提示词列表: ${JSON.stringify(result.prompts)}`, 'info');
        requestResultTextarea.value = JSON.stringify(result, null, 2);
    } catch (error) {
        log(`列出提示词失败: ${error.message}`, 'error');
        requestResultTextarea.value = `列出提示词失败: ${error.message}`;
    }
});

// 获取提示词按钮点击事件
getPromptBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        // 先列出提示词以获取可用提示词ID
        log('正在获取提示词列表...', 'info');
        const promptsResult = await client.listPrompts({});
        
        if (promptsResult.prompts && promptsResult.prompts.length > 0) {
            const firstPromptId = promptsResult.prompts[0].id;
            log(`使用WebSocket Client API获取提示词: ${firstPromptId}`, 'info');
            
            const result = await client.getPrompt({ id: firstPromptId });
            
            log('获取提示词成功', 'info');
            requestResultTextarea.value = JSON.stringify(result, null, 2);
        } else {
            log('未找到可用提示词', 'info');
            requestResultTextarea.value = '未找到可用提示词';
        }
    } catch (error) {
        log(`获取提示词失败: ${error.message}`, 'error');
        requestResultTextarea.value = `获取提示词失败: ${error.message}`;
    }
});

// 列出资源按钮点击事件
listResourcesBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        log('使用WebSocket Client API列出资源...', 'info');
        const result = await client.listResources({});
        
        log(`资源列表: ${JSON.stringify(result.resources)}`, 'info');
        requestResultTextarea.value = JSON.stringify(result, null, 2);
    } catch (error) {
        log(`列出资源失败: ${error.message}`, 'error');
        requestResultTextarea.value = `列出资源失败: ${error.message}`;
    }
});

// 读取资源按钮点击事件
readResourceBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        // 先列出资源以获取可用资源ID
        log('正在获取资源列表...', 'info');
        const resourcesResult = await client.listResources({});
        
        if (resourcesResult.resources && resourcesResult.resources.length > 0) {
            const firstResourceId = resourcesResult.resources[0].id;
            log(`使用WebSocket Client API读取资源: ${firstResourceId}`, 'info');
            
            const result = await client.readResource({ id: firstResourceId });
            
            log('读取资源成功', 'info');
            requestResultTextarea.value = JSON.stringify(result, null, 2);
        } else {
            log('未找到可用资源', 'info');
            requestResultTextarea.value = '未找到可用资源';
        }
    } catch (error) {
        log(`读取资源失败: ${error.message}`, 'error');
        requestResultTextarea.value = `读取资源失败: ${error.message}`;
    }
});

// 列出资源模板按钮点击事件
listResourceTemplatesBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        log('使用WebSocket Client API列出资源模板...', 'info');
        const result = await client.listResourceTemplates({});
        
        log(`资源模板列表: ${JSON.stringify(result.templates)}`, 'info');
        requestResultTextarea.value = JSON.stringify(result, null, 2);
    } catch (error) {
        log(`列出资源模板失败: ${error.message}`, 'error');
        requestResultTextarea.value = `列出资源模板失败: ${error.message}`;
    }
});

// 订阅资源按钮点击事件
subscribeResourceBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        // 先列出资源以获取可用资源ID
        log('正在获取资源列表...', 'info');
        const resourcesResult = await client.listResources({});
        
        if (resourcesResult.resources && resourcesResult.resources.length > 0) {
            const firstResourceId = resourcesResult.resources[0].id;
            log(`使用WebSocket Client API订阅资源: ${firstResourceId}`, 'info');
            
            await client.subscribeResource({ id: firstResourceId });
            
            log('资源订阅成功', 'info');
            requestResultTextarea.value = `资源 ${firstResourceId} 订阅成功`;
        } else {
            log('未找到可用资源', 'info');
            requestResultTextarea.value = '未找到可用资源';
        }
    } catch (error) {
        log(`订阅资源失败: ${error.message}`, 'error');
        requestResultTextarea.value = `订阅资源失败: ${error.message}`;
    }
});

// 取消订阅资源按钮点击事件
unsubscribeResourceBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        // 先列出资源以获取可用资源ID
        log('正在获取资源列表...', 'info');
        const resourcesResult = await client.listResources({});
        
        if (resourcesResult.resources && resourcesResult.resources.length > 0) {
            const firstResourceId = resourcesResult.resources[0].id;
            log(`使用WebSocket Client API取消订阅资源: ${firstResourceId}`, 'info');
            
            await client.unsubscribeResource({ id: firstResourceId });
            
            log('取消资源订阅成功', 'info');
            requestResultTextarea.value = `资源 ${firstResourceId} 取消订阅成功`;
        } else {
            log('未找到可用资源', 'info');
            requestResultTextarea.value = '未找到可用资源';
        }
    } catch (error) {
        log(`取消订阅资源失败: ${error.message}`, 'error');
        requestResultTextarea.value = `取消订阅资源失败: ${error.message}`;
    }
});

// 获取服务器信息按钮点击事件
getServerInfoBtn.addEventListener('click', () => {
    if (client) {
        const serverInfo = client.getServerVersion();
        const serverCapabilities = client.getServerCapabilities();
        const instructions = client.getInstructions();
        
        const info = {
            serverInfo: serverInfo,
            serverCapabilities: serverCapabilities,
            instructions: instructions
        };
        
        log(`获取服务器信息: ${JSON.stringify(info)}`, 'info');
        requestResultTextarea.value = JSON.stringify(info, null, 2);
    } else {
        log('错误: 客户端未初始化', 'error');
        requestResultTextarea.value = '客户端未初始化，请先连接服务器';
    }
});

// 自定义请求按钮点击事件
customRequestBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        // 这里演示一个自定义的补全请求
        const requestData = {
            "jsonrpc": "2.0",
            "method": "completion/complete",
            "params": {
                "prompt": "请解释什么是MCP协议？",
                "maxTokens": 200
            },
            "id": "custom-completion-1"
        };
        
        log(`使用WebSocket Client API发送自定义请求: ${JSON.stringify(requestData)}`, 'info');
        
        const result = await client.request(requestData);
        log(`请求结果: ${JSON.stringify(result)}`, 'info');
        requestResultTextarea.value = JSON.stringify(result, null, 2);
        
    } catch (error) {
        log(`请求失败: ${error.message}`, 'error');
        requestResultTextarea.value = `请求失败: ${error.message}`;
    }
});

// 发送请求按钮点击事件
sendRequestBtn.addEventListener('click', async () => {
    try {
        if (!client) {
            log('错误: 客户端未初始化', 'error');
            return;
        }
        
        const method = requestMethodSelect.value;
        let params;
        
        try {
            // 添加防御性检查，确保JSON对象存在
            if (typeof JSON === 'undefined') {
                throw new Error('JSON对象不可用');
            }
            params = JSON.parse(requestParamsInput.value.trim() || '{}');
        } catch (e) {
            log(`参数格式错误: ${e.message}`, 'error');
            return;
        }
        
        log(`使用WebSocket Client API发送${method}请求`, 'info');
        
        // 构建请求对象
        const requestData = {
            "jsonrpc": "2.0",
            "method": method,
            "params": params,
            "id": `req-${Date.now()}`
        };
        
        // 使用Client API发送请求
        const result = await client.request(requestData);
        
        log(`请求成功，收到响应`, 'info');
        requestResultTextarea.value = JSON.stringify(result, null, 2);
        
    } catch (error) {
        log(`请求失败: ${error.message}`, 'error');
        requestResultTextarea.value = `请求失败: ${error.message}`;
    }
});

// 断开连接按钮点击事件
disconnectBtn.addEventListener('click', async () => {
    if (transport) {
        log('正在断开WebSocket连接...', 'info');
        try {
            await transport.close();
            log('WebSocket连接已成功关闭', 'info');
        } catch (error) {
            log(`关闭WebSocket连接时出错: ${error.message}`, 'error');
        }
        
        transport = null;
        client = null; // 清理client实例
        resumptionToken = null;
        resumptionTokenSpan.textContent = '无';
        sessionIdSpan.textContent = '未连接';
        serverInfoSpan.textContent = '无';
        connectionStatusSpan.textContent = '未连接';
        
        // 重新启用能力选择框
        disableCapabilityCheckboxes(false);
        
        updateUIState(false);
        
        // 清空结果区域
        requestResultTextarea.value = '';
    }
});

// 终止会话按钮点击事件
terminateSessionBtn.addEventListener('click', async () => {
    if (transport && transport.sessionId) {
        log(`正在终止WebSocket会话 ${transport.sessionId}...`, 'info');
        try {
            await transport.terminateSession();
            log('WebSocket会话已终止', 'info');
            sessionIdSpan.textContent = '已终止';
        } catch (error) {
            log(`终止WebSocket会话失败: ${error.message}`, 'error');
        }
    }
});

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', () => {
    log('WebSocket Client 客户端示例已加载', 'info');
    log('请输入WebSocket服务器 URL 并点击连接按钮开始演示', 'info');
    
    // 初始化UI状态
    updateUIState(false);
});